package com.mti.zhpt.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mti.zhpt.dao.*;
import com.mti.zhpt.shared.Exception.BusinessException;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.mti.zhpt.model.EventTimerEntity;
import com.mti.zhpt.model.EventTimerFileEntity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * @Description: 案事件
 * @Author: zhaopf@mti-sh.cn
 * @Date: 2019/4/18 11:14
 */
@Service("eventDetailsServiceImpl")
@Slf4j
public class EventDetailsServiceImpl implements Comparator<Object> {

    @Resource
    private EventDetailsMapper eventDetailsMapper;
    @Resource
    private EventDetailsTimerMapper eventDetailsTimerMapper;
    @Resource
    private EventTimerPhotoMapper eventTimerPhotoMapper;
    @Resource
    private EventRefPersonMapper eventRefPersonMapper;
    @Resource
    private EventPowerMapper eventPowerMapper;

    @Resource
    private RequestLeaderMapper requestLeaderMapper;

    @Resource
    CommandReserveMapper commandReserveMapper;

    public Map<Object, Object> queryDetails(String eventId) {
        Map<Object, Object> mapResult = new HashMap<>();
        try {
            /**
             * 1、查找事件详情
             */
            Map<String, Object> detailsEntity = eventDetailsMapper.queryDetails(eventId);
            Double[] coordinates = {(Double) detailsEntity.get("longitude"), (Double) detailsEntity.get("latitude")};
            detailsEntity.put("coordinates", coordinates);
            mapResult.put("eventDetailsEntity", detailsEntity);
            /*
             * if (!CollectionUtils.isEmpty(detailsEntityList)){ EventDetailsEntity
             * eventDetailsEntity = detailsEntityList.get(0);
             * mapResult.put("eventDetailsEntity", eventDetailsEntity); }
             */
            /**
             *
             * 2、时间轴---- 封装相关时间轴图片/添加请示汇报反馈内容
             *
             */
            List<EventTimerEntity> timerEntities = eventDetailsTimerMapper.queryDetailsTimer(eventId);

            for (EventTimerEntity timerEntity : timerEntities) {
                if (timerEntity.getTimerId() != null) {
                    /**
                     * 根据命令id 查找命令相关图片、音频、视频。
                     */
                    List<EventTimerFileEntity> timerFileEntityList = eventTimerPhotoMapper
                            .queryFile(timerEntity.getTimerId());

                    List<String> imagesUrl = new ArrayList<>();
                    List<String> videosUrl = new ArrayList<>();
                    List<Map<Object, Object>> audios = new ArrayList<>();
                    if (!CollectionUtils.isEmpty(timerFileEntityList)) {
                        for (EventTimerFileEntity timerFileEntity : timerFileEntityList) {
                            String fileName = timerFileEntity.getPhotoAddress();
                            if (fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".JPEG")) {
                                imagesUrl.add(fileName);
                            } else if (fileName.endsWith(".mp4")) {
                                videosUrl.add(fileName);
                            } else if (fileName.endsWith(".wav")) {
                                Map<Object, Object> map = new HashMap<>();
                                map.put("recordMp3Length", timerFileEntity.getRecordMp3Length());
                                map.put("record", timerFileEntity.getRecord());
                                map.put("audiosUrl", fileName);
                                audios.add(map);
                            }
                        }
                        timerEntity.setPhotoEntityList(timerFileEntityList);
                        timerEntity.setImagesUrl(imagesUrl);
                        timerEntity.setVideosUrl(videosUrl);
                        timerEntity.setAudios(audios);
                    }
                }
               if (!ObjectUtils.isEmpty(timerEntity.getTasksId())){
                   Integer tasksStatus = eventDetailsTimerMapper.queryTasksStatus(timerEntity.getTasksId());
                   timerEntity.setStatus(tasksStatus);
               }


            }
            /*
             * List<Map<String, Object>> maps =
             * requestLeaderMapper.queryresponseList(eventId); for (Map<String, Object> map
             * : maps) { EventTimerEntity entity = new EventTimerEntity();
             * entity.setEventId((Integer) map.get("eventid")); entity.setCreateTime((Date)
             * map.get("createtime")); entity.setFeedback((String) map.get("feedback"));
             * entity.setRemark((String) map.get("content")); entity.setPoliceName((String)
             * map.get("police_name")); entity.setStatus((Integer) map.get("status"));
             * timerEntities.add(entity); }
             */

            /**
             * 日期排序
             */
            /*
             * EventDetailsServiceImpl sortClass = new EventDetailsServiceImpl();
             * Collections.sort(timerEntities, sortClass);
             */
            mapResult.put("timerEntities", timerEntities);
            /**
             * 3、查找相关人
             */
            List<Map<String, Object>> eventRefPersons = eventRefPersonMapper.queryEventRefPersons(eventId);
            mapResult.put("eventRefPersons", eventRefPersons);

//			/**
//			 * 4、参战力量单位总数
//			 */
//            List<Map<String, Object>> eventPowers = eventPowerMapper.queryEventPowers(eventId);
//            mapResult.put("powers", eventPowers);

            /**
             * 参战力量
             */
            // 参战单位
//            List<Map<Object, Object>> unitTask = commandReserveMapper.queryTaskCommand(eventId);
//            mapResult.put("unitTask", unitTask);
            // 参战警力（参战人员）
//            List<Map<Object, Object>> policeTask = commandReserveMapper.queryTaskPolice(eventId);
//            mapResult.put("policeTask", policeTask);

            /**
             *  新参战力量
             */
            mapResult = sumPolice(eventId, mapResult);


        } catch (Exception e) {
            log.error("查找事件信息、时间轴错误：",e);
            throw new BusinessException("查找事件信息、时间轴错误：",e);
        }

        return mapResult;
    }

    public Map<Object, Object> sumPolice(String eventId, Map<Object, Object> mapResult) {
        //参战单位
        List<Map<Object, Object>> unitTask = commandReserveMapper.queryUnitTask(eventId);
        mapResult.put("unitTask", unitTask);
        Long reach_number = 0L;
        Long dispatch_number = 0L;
        Long reserve_number = 0L;

        for (Map<Object, Object> objectObjectMap : unitTask) {
            reach_number += (long) objectObjectMap.get("reach_number");  //到场
            dispatch_number += (long) objectObjectMap.get("dispatch_number");//出动
            reserve_number += (long) objectObjectMap.get("reserve_number");//备勤
        }

        //参战人员 ：出动、到场人数
        List<Map<Object, Object>> policeNumber = commandReserveMapper.queryPoliceNumber(eventId);
        Map<Object, Object> policeNumberMap = policeNumber.get(0);
        Long dispatch_number_ry = 0L;
        Long reach_number_ry = 0L;
        if (!ObjectUtils.isEmpty(policeNumberMap)){
             dispatch_number_ry = (long) policeNumberMap.get("dispatch_number");
             reach_number_ry = (long) policeNumberMap.get("reach_number");
        }


        /**
         * 总警力
         */
        Map<String, Object> sumData = new HashMap<>();
        sumData.put("sumForces",reserve_number+dispatch_number+ ( dispatch_number_ry)+reach_number+ ( reach_number_ry));
        sumData.put("sumReserveNumber",reserve_number);
        sumData.put("sumDispatchNumber",dispatch_number+ ( dispatch_number_ry));
        sumData.put("sumReachNumber",reach_number+ ( reach_number_ry));

        mapResult.put("powers", sumData);


        List<Map<Object, Object>> policeTask = commandReserveMapper.newQueryTaskPolice(eventId);
        mapResult.put("policeTask", policeTask);
        return mapResult ;
    }

    @Override
    public int compare(Object o1, Object o2) {
        EventTimerEntity user1 = (EventTimerEntity) o1;
        EventTimerEntity user2 = (EventTimerEntity) o2;
        Date begin = user1.getCreateTime();
        Date end = user2.getCreateTime();

        if (begin.after(end)) {
            return -1;
        } else {
            return 1;
        }
    }
}
